package com.nercel.dsj.gksales.config;

import com.nercel.dsj.gksales.model.QueryParams;
import com.nercel.dsj.gksales.util.StringUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author sunlin
 * @date 2018-10-30
 */
public class PageHandArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 用于判定是否需要处理该参数分解，返回true为需要，并会去调用下面的方法resolveArgument
     * 判断Controller中是否有RequestPage对象接收分页参数
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        if (QueryParams.class.equals(methodParameter.getParameterType())) {
            return true;
        }
        return false;
    }

    /**
     * resolveArgument：真正用于处理参数分解的方法，返回的Object就是controller方法上的形参对象。
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //String sort = nativeWebRequest.getParameter("sort");
        //log.debug("pageSize:{},pageNumber:{},sort:{}", pageSize, pageNumber, StringUtil.camel2Underline(sort));
        // 对 sort字段的参数进行解析为 SQL能够识别的数据 如 id desc，name asc
        String pageSize = nativeWebRequest.getParameter("pageSize");
        String pageNumber = nativeWebRequest.getParameter("page");
        QueryParams requestPage = new QueryParams();
        if (StringUtil.isNumber(pageSize)) {
            requestPage.setPageSize(Integer.parseInt(pageSize));
        }
        if (StringUtil.isNumber(pageNumber)) {
            requestPage.setPageNumber(Integer.parseInt(pageNumber));
        }
        return requestPage;
    }
}

